# jsb/plugs/gozer/birthday.py
#
#

""" manage birthdays """

## jsb imports

from jsb.utils.timeutils import bdmonths, getdaymonth, strtotime, elapsedstring
from jsb.utils.generic import getwho
from jsb.utils.exception import handle_exception
from jsb.lib.users import users
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.config import getmainconfig

## basic imports

import time
import re

## SA imports

from jsb.database.alchemy import Base, create_session, trans, transfunc, create_all, startmaindb, query
from datetime import datetime
from time import localtime
from sqlalchemy import Column, String, Integer, Text, DateTime, ForeignKey, Sequence
import sqlalchemy as sa

class Birthday(Base):
    __tablename__ = 'birthday'
    __table_args__ = {'useexisting': True}
    name = Column('name', String(255), primary_key=True)
    birthday = Column('birthday', String(255), nullable=False)

    def __init__(self, name, birthday):
        self.name = name
        self.birthday = birthday

create_all('birthday')

@transfunc
def handle_bdset(session, bot, ievent):
    """ bd-set <date> .. set birthday """
    try:
        what = ievent.args[0]
        if not re.search('\d*\d-\d*\d-\d\d\d\d', what): ievent.reply('i need a date in the format day-month-year') ; return
    except IndexError: ievent.missing('<date>') ; return
    name = users.getname(ievent.userhost)
    if not name: ievent.reply("can't find a user for %s" % ievent.userhost) ; return
    bd = query(Birthday).filter(Birthday.name==name).first()
    if not bd: bd = Birthday(name, what) ; session.add(bd) ; session.commit()
    else: bd.birthday = what
    ievent.reply('birthday set')

cmnds.add('bd-set', handle_bdset, 'USER')
examples.add('bd-set', 'bd-set <date> .. set birthday', 'bd-set 3-11-1967')

@transfunc
def handle_bddel(session, bot, ievent):
    """ bd-del .. delete birthday """
    name = users.getname(ievent.userhost)
    result = 0
    bd = session.query(Birthday).filter(Birthday.name==name).first()
    if not bd: ievent.reply('no birthday known for %s (%s)' % (ievent.nick, name))
    else: session.delete(bd) ; session.commit() ; ievent.reply('birthday removed')

cmnds.add('bd-del', handle_bddel, 'USER')
examples.add('bd-del', 'delete birthday data', 'bd-del')

def handle_bd(bot, ievent):
    """ bd [<nr|user>] .. show birthday of month or user """
    if not ievent.rest: handle_checkbd(bot, ievent) ; return
    try:
        int(ievent.args[0])
        handle_checkbd2(bot, ievent)
        return
    except (IndexError, ValueError): who = ievent.args[0]
    userhost = getwho(bot, who)
    if not userhost: ievent.reply("don't know userhost of %s" % who) ; return
    name = users.getname(userhost)
    if not name: ievent.reply("can't find user for %s" % userhost) ; return
    bd = query(Birthday).filter(Birthday.name==name).first()
    if bd: ievent.reply('birthday of %s is %s' % (who, bd.birthday))
    else: ievent.reply('no birthday know for %s' % name)

cmnds.add('bd', handle_bd, ['USER', 'WEB'])
examples.add('bd', 'bd [<nr|user>] .. show birthdays for this month or show birthday of <nick>', '1) bd 2) bd dunker')

def handle_checkbd(bot, ievent):
    """ bd-check .. check birthdays for current month """
    (nowday, nowmonth) = getdaymonth(time.time())
    mstr = ""
    result = []
    bds = query(Birthday).all()
    if not bds: ievent.reply('no birthdays this month') ; return
    for i in bds:
        btime = strtotime(i.birthday)
        if btime == None: continue
        (day, month) = getdaymonth(btime)
        if month == nowmonth:
            result.append((int(day), i.name, i.birthday))
            if day == nowday and month == nowmonth: ievent.reply("it's %s's birthday today!" % i.name)
    result.sort(lambda x, y: cmp(x[0], y[0]))
    for i in result: mstr += "%s: %s " % (i[1], i[2])
    if mstr: mstr = "birthdays this month = " + mstr ; ievent.reply(mstr)
    else: ievent.reply('no birthdays this month')

def handle_checkbd2(bot, ievent):
    """ bd-check <nr> .. show birthdays in month (by number) """
    try:
        monthnr = int(ievent.args[0])
        if monthnr < 1 or monthnr > 12: ievent.reply("number must be between 1 and 12") ; return
    except (IndexError, ValueError): ievent.missing('<monthnr>') ; return
    mstr = ""
    result = []
    bds = query(Birthday).all()
    if not bds: ievent.reply('no birthdays known') ; return
    for i in bds:
        btime = strtotime(i.birthday)
        if btime == None: continue
        (day, month) = getdaymonth(btime)
        if month == bdmonths[monthnr]: result.append((int(day), i.name, i.birthday))
    result.sort(lambda x, y: cmp(x[0], y[0]))
    for i in result: mstr += "%s: %s " % (i[1], i[2])
    if mstr: mstr = "birthdays in %s = " % bdmonths[monthnr] + mstr ; ievent.reply(mstr)
    else: ievent.reply('no birthdays found for %s' % bdmonths[monthnr])

def handle_age(bot, ievent):
    """ age <nick> .. show age of user """
    try: who = ievent.args[0]
    except IndexError: ievent.missing('<nick>') ; return
    userhost = getwho(bot, who)
    if not userhost: ievent.reply("don't know userhost of %s" % who) ; return
    name = users.getname(userhost)
    if not name: ievent.reply("can't find user for %s" % userhost) ; return
    bd = query(Birthday).filter(Birthday.name==name).first()
    try: birthday = bd.birthday
    except (TypeError, AttributeError): ievent.reply("can't find birthday data for %s" % who) ; return
    btime = strtotime(birthday)
    if btime == None: ievent.reply("can't make a date out of %s" % birthday) ; return
    age = int(time.time()) - int(btime)
    ievent.reply("age of %s is %s" % (who, elapsedstring(age, ywd=True)))

cmnds.add('age', handle_age, ['USER', 'WEB'])
examples.add('age', 'age <nick> .. show how old <nick> is', 'age dunker')
